from django.shortcuts import render, redirect

from rest_framework.views import APIView
from upload.fdfs_storage import FastDFSStorage
from django.conf import settings
from rest_framework.response import Response

# Create your views here.

class ImageUploadViewForAvatar(APIView):
    def post(self, request):
        storage = FastDFSStorage()
        img_files = request.FILES.get('img')
        img = img_files.read()
        ret = storage._save("", content = img)
        print(ret)
        print(request.data.get("img"))
        ret_url = settings.FDFS_URL + ret
        return Response({"imgurl": ret_url})


class ImageUploadForCKEditorView(APIView):

    def post(self,request):
        from_address = request.META['HTTP_REFERER']
        print(request.META)
        from_address = from_address[:from_address.rfind('/'):]

        client = FastDFSStorage()
        upload_img = request.FILES.get('upload')
        print(upload_img)
        img = client._save(name = None,content=upload_img.read())
        img_url = client.url(img)
        img_url = from_address + '/upload_success.html?image_url=' + img_url + '&CKEditorFuncNum=' + request.query_params.get('CKEditorFuncNum')

        return redirect(img_url)